package view
{
	import __AS3__.vec.Vector;
	
	import flash.display.DisplayObjectContainer;
	import flash.display.Graphics;
	import flash.display.MovieClip;
	
	public class Graphic
	{
		private var _mc:MovieClip;
		
		private var _vecIntervals:Vector.<Number>;
		
		private var _nMinValueX:Number;
		private var _nMaxValueX:Number;
		private var _nDValueX:Number;
		private var _nInvDValueX:Number;
		
		private var _uColor:uint = 0x0;
		
		private var _nScale:Number = 1;
		
		//мода распределения
		//http://ru.wikipedia.org/wiki/%D0%9C%D0%BE%D0%B4%D0%B0_%28%D1%81%D1%82%D0%B0%D1%82%D0%B8%D1%81%D1%82%D0%B8%D0%BA%D0%B0%29
		private var _nModeValueSum:int = 0;
		
		private var _nExperimentsSum:int = 0;
		
		private var _nHeight:Number = 100;
		
		public function Graphic(mcParent:DisplayObjectContainer, nIntervals:int, nMinValueX:Number, nMaxValueX:Number)
		{
			_mc = new MovieClip;
			mcParent.addChild(_mc);
			
			_nMinValueX = nMinValueX;
			_nMaxValueX = nMaxValueX;
			_nDValueX = nMaxValueX - nMinValueX;
			_nInvDValueX = 1 / _nDValueX; 
			_vecIntervals = new Vector.<Number> (nIntervals);
			var nIndex:int = _vecIntervals.length;
			while(--nIndex>=0)
			{
				_vecIntervals[nIndex] = 0;
			}
		}
		
		public function set x(nValue:int):void 
		{ 
			_mc.x = nValue;
		}
		
		public function set y(nValue:int):void 
		{ 
			_mc.y = nValue;
		}	 
		
		public function get color():uint { return _uColor;}
		public function set color(uValue:uint):void
		{
			_uColor = uValue;
		}
		
		public function get scale():Number { return _nScale;}
		public function set scale(nValue:Number):void 
		{ 
			_nScale = nValue;
		}

		public function draw():void
		{
			var gr:Graphics = _mc.graphics;
			gr.clear();
			gr.lineStyle(0x0, color);
			gr.beginFill(color, 0.5);
			var nCount:int = _vecIntervals.length;
			var nIndex:int = nCount;
			gr.moveTo(_nDValueX * scale *(nCount-1) / nCount, 0); 
			while(--nIndex>=0)
			{
				var nX:Number = _nMinValueX + _nDValueX * nIndex / nCount;
				var nY:Number = _vecIntervals[nIndex];
				
				//нормализуем
				nX *= scale;
				nY = nY / _nModeValueSum * _nHeight;
				
				gr.lineTo(nX, -nY);
			}
			gr.lineTo(0, 0);
						
			gr.endFill();
		}
		
		public function addExperiment(nValue:Number):void
		{
			var nIndex:int =  getIndexByValue(nValue);
			var nValueDensity:int = _vecIntervals[nIndex];
			_vecIntervals[nIndex] = nValueDensity + 1;
			_nExperimentsSum++;
			if(_nModeValueSum < nValueDensity)
			{
				_nModeValueSum = nValueDensity;
			} 						
		}
		
		private function getIndexByValue(nValue:Number):int
		{
			return _nInvDValueX * (nValue - _nMinValueX) * (_vecIntervals.length - 1);
		}
	}
}